﻿//Copyright (c) Microsoft Corporation. All rights reserved.

using Microsoft.Ted.Wacel.TestConsole.Properties;
using Microsoft.Ted.Wacel.TableStorage;
using System;
using System.Diagnostics;
using System.Threading;

namespace Microsoft.Ted.Wacel.TestConsole
{
    public class SyncRootTester
    {
        public static void LockTest()
        {
            CloudSyncRoot syncRoot = new CloudSyncRoot(Settings.Default.StorageConnectionString, "mylocks");

            double value = 0;
            ManualResetEvent[] handles = new ManualResetEvent[5];
            for (int i = 0; i < 5; i++)
                handles[i] = new ManualResetEvent(false);
            
            for (int i = 0; i <5; i++)
            {
                ThreadPool.QueueUserWorkItem((obj) =>
                    {
                        Stopwatch watch = new Stopwatch();
                        int index = (int)obj;
                        for (int j = 0; j < 10; j++)
                        {
                            watch.Restart();
                            string lease = syncRoot.Accquire("alock", TimeSpan.FromSeconds(15));
                            watch.Stop();
                            Console.WriteLine("Time to acquire lock: " + watch.ElapsedMilliseconds);
                            double oldValue = value;
                            Thread.Sleep(200);
                            value++;
                            if (oldValue+1 != value)
                                throw new Exception("Thread violation");
                            
                            syncRoot.Release("alock", lease);
                        }
                        handles[index].Set();
                    }, i);
            }

            WaitHandle.WaitAll(handles);
            VisualTester.AreEqual(50, value);
        }
    }
   
}
